#!/bin/bash
ctime="$(date +%Y"-"%m"-"%d" "%k":"%M":"%S)";
year=$(date +%Y);
logFile="/var/log/backup/backup_doc_${year}.log";
if [ ! -f "$logFile" ];
then 
    touch $logFile;
fi
# ======================== fun getTime  ========================
function getTime(){
    echo $(date +%Y"-"%m"-"%d" "%k":"%M":"%S);
}

echo $(getTime) doc files backup command excute starting.....  >> $logFile;



# source path
sourcedir="/var2/share/resource_library";
#specialdir="/var2/share/maintenance_Library";
specialdir="/var2/share";
specialfile="maintenance_Library";
# back dir
backupdir="/var/backup/doc_bak";

if [ ! -d "$backupdir" ];then
	echo $(getTime) "Error!!!backupdir is not found!" >> $logFile;
	echo $(getTime) =================================doc backup opration failed!!! >> $logFile;
fi
# $1:scourse path $2:source file 
function backupfiles()
{
    echo $(getTime) begin backup $1/$2 ...  >> $logFile; 
    cd $1
    # delete old file
    oldfile="$backupdir"/"$2"_"$year".tar.bz2
    if [ -f "$oldfile" ];
    then 
        echo $(getTime) $oldfile is exits "(" old ")" , deleting now. >> $logFile;
        rm -rf $oldfile;
    else
        echo $(getTime) $oldfile is not exits, will create later.  >> $logFile;
    fi
    tmpfile=/tmp/$2_$year.tar.bz2
    # tar compress
    tar -jpc -f $tmpfile $2
    echo $(getTime) tmpfile compress completed! >> $logFile;
    # mv to dir
    if [ ! -f "$tmpfile" ];
    then
        echo $(getTime) tmpfile is not found, $2 backup opration failed!! >> $logFile;
    else
        echo $(getTime) tmpfile is OK, mv to nas. >> $logFile;
        # mv tar file
        mv $tmpfile $backupdir/
    fi
    echo $(getTime) ----backup function end  >> $logFile; 
}
backupfiles "$specialdir" "$specialfile";
arr=("01-公司规范库/01-公司制度" "03-产品设计库" "04-产品研发库" "05-项目库" "06-售后" "07-人事" "08-财务" "09-商务" "10-公司管理" "12-方案库" "13-申报");
for i in ${arr[@]}
do
	backupfiles "$sourcedir" "$i";
done

echo $(getTime) =================================doc backup opration success!!! >> $logFile;
